import java.io.*;
import java.net.*;
import java.util.*;


public class Client {
	public static GameState game;
	public static UserInterface ui;
	public static Communication c;
	public static void main(String args[]) {
		c = new Communication("192.168.1.116",1337);
		ui = new UserInterface();
		ui.update();
		new Thread(c).start();
	}
	public static void handle(Message m) {
		switch (m.type) {
		case Message.DISPLAY:
			ui.alert(m.text);
			break;
		case Message.UPDATE:
			System.out.println(m.g.chat.messages.toString());
			game = m.g;
			System.out.println(game.chat.messages.toString());
			ui.update();
			break;
		}
	}
	protected static class Communication implements Runnable {
		public static Socket socket;
		public static ObjectOutputStream objout;
		public static ObjectInputStream objin;
		public static LinkedList<Message> tosend = new LinkedList<Message>();
		public Communication(String host, int port){
			try {
				socket = new Socket(host,port);
				socket.setSoTimeout(100);
				objout = new ObjectOutputStream(socket.getOutputStream());
				objin = new ObjectInputStream(socket.getInputStream());
				try {
					game = (GameState)objin.readObject();
				} catch (ClassNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} catch (UnknownHostException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		public void sendMessage(Message m) {
			try {
				objout.writeObject(m);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		public void run() {
			Message m = null;
			while(true) {
				try {
					m = (Message)objin.readObject();
				} catch (IOException e) {
				} catch (ClassNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				if(m != null) {
					Client.handle(m);
					m = null;
				}
				while(!tosend.isEmpty()) {
					m = tosend.removeFirst();
					sendMessage(m);
					m = null;
				}
			}
		}
	}
}
